package com.juxfe.bookmanagement.controller;

import com.juxfe.bookmanagement.model.User;
import com.juxfe.bookmanagement.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 显示首页
     */
    @GetMapping("/")
    public String index() {
        return "index";
    }

    /**
     * 显示登录页面
     */
    @GetMapping("/login")
    public String showLoginPage() {
        return "login";
    }

    /**
     * 处理登录请求
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        Model model) {
        User user = userService.login(username, password);
        if (user != null) {
            // 登录成功，将用户信息存入session
            session.setAttribute("user", user);
            return "redirect:/";
        } else {
            // 登录失败
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
    }

    /**
     * 显示注册页面
     */
    @GetMapping("/register")
    public String showRegisterPage() {
        return "register";
    }

    /**
     * 处理注册请求
     */
    @PostMapping("/register")
    public String register(@ModelAttribute User user, Model model) {
        // 检查用户名是否已存在
        if (userService.checkUsernameExists(user.getUsername())) {
            model.addAttribute("error", "用户名已存在");
            return "register";
        }

        // 注册用户
        boolean result = userService.register(user);
        if (result) {
            return "redirect:/login?registered=true";
        } else {
            model.addAttribute("error", "注册失败，请重试");
            return "register";
        }
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 清除session
        session.invalidate();
        return "redirect:/login";
    }
}
